package com.westcom.healthmate.controller;

import com.westcom.healthmate.bean.MiraSleepDailyEvaluate;
import com.westcom.healthmate.bean.MiraSleepDailyReport;
import com.westcom.healthmate.bean.ResponseBean;
import com.westcom.healthmate.common.constants.ErrorConstants;
import com.westcom.healthmate.common.exception.ErrorException;
import com.westcom.healthmate.common.utils.CommonUtils;
import com.westcom.healthmate.dao.ThirdPartInfoDao;
import com.westcom.healthmate.po.MiraSleepDataPo;
import com.westcom.healthmate.po.ThirdPartInfoPo;
import com.westcom.healthmate.service.MiraService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController()
public class MiraController extends BasicController
{
    @Autowired
    MiraService mira;

    @Autowired
    ThirdPartInfoDao thridDao;

    private static final Logger logger = LoggerFactory.getLogger(MiraController.class);

    @RequestMapping(path="test",method={RequestMethod.GET})
    public ResponseBean test(HttpServletRequest req, HttpServletResponse resp)
    {
        ResponseBean bean = new ResponseBean();
        List<ThirdPartInfoPo> all =thridDao.findAll();
        return bean;
    }

    @RequestMapping(path="mira/evaluate/{userId}/{sensorId}/{st}/{et}",method={RequestMethod.GET})
    public ResponseBean getSleepEvaluate(HttpServletRequest req, HttpServletResponse resp,
                                         @PathVariable("userId") int userId,
                                         @PathVariable("sensorId") int sensorId,
                                         @PathVariable("st") long st,
                                         @PathVariable("et") long et)
    {
        try
        {
            MiraSleepDailyEvaluate evaluate = mira.getSleepEvaluate(userId,sensorId,st,et);
            return CommonUtils.getResponse(ErrorConstants.SUCCESS,evaluate,resp);
        } catch (ErrorException e)
        {
            e.printStackTrace();
            logger.error("get mira sleep evaluate failed,userId:{},sensorId:{},st:{},et:{}",userId,sensorId,st,et);
            return CommonUtils.getResponse(e.getCode(),null,resp);
        }
    }

    @RequestMapping(path="mira/report/{userId}/{sensorId}/{st}/{et}",method={RequestMethod.GET})
    public ResponseBean getSleepReport(HttpServletRequest req, HttpServletResponse resp,
                                         @PathVariable("userId") int userId,
                                         @PathVariable("sensorId") int sensorId,
                                         @PathVariable("st") long st,
                                         @PathVariable("et") long et)
    {
        try
        {
            MiraSleepDailyReport report = mira.getSleepReport(userId,sensorId,st,et);
            return CommonUtils.getResponse(ErrorConstants.SUCCESS,report,resp);
        } catch (ErrorException e)
        {
            e.printStackTrace();
            logger.error("get mira sleep evaluate failed,userId:{},sensorId:{},st:{},et:{}",userId,sensorId,st,et);
            return CommonUtils.getResponse(e.getCode(),null,resp);
        }
    }

    @RequestMapping(path="mira/sleep-data",method={RequestMethod.POST})
    public ResponseBean saveSleepData(HttpServletRequest req, HttpServletResponse resp)
    {
        try
        {
            ServletInputStream ins = null;
            try
            {
                ins = req.getInputStream();
            } catch (IOException e)
            {
                e.printStackTrace();
                logger.error("get inputStream failed,msg:{}",e.getMessage());
                return CommonUtils.getResponse(ErrorConstants.IO_ERROR,null,resp);
            }
            byte[] buffer = new byte[1024];
            int offset = 0;
            while(true)
            {
                int read = 0;
                try
                {
                    read = ins.read(buffer,offset,buffer.length - offset);
                } catch (IOException e)
                {
                    e.printStackTrace();
                    logger.error("read data failed,msg:{}",e.getMessage());
                    return CommonUtils.getResponse(ErrorConstants.IO_ERROR,null,resp);
                }
                if(read <0)
                {
                    break;
                }
                offset = offset + read;
                if(offset >= buffer.length)
                {
                    break;
                }
            }
            String mac = req.getHeader("mac");
            List<MiraSleepDataPo> pos = mira.saveDataFromBytes(mac,CommonUtils.sliceArray(buffer,0,offset));
            String msg = String.format("saved:%d", CollectionUtils.isEmpty(pos)?0:pos.size());
            logger.info("mac:{},data:{},msg:{}",mac,CommonUtils.bytes2HexStr(buffer,offset),msg);
            return CommonUtils.getResponse(ErrorConstants.SUCCESS,msg,resp);
        } catch (ErrorException e)
        {
            e.printStackTrace();
            return CommonUtils.getResponse(e.getCode(),null,resp);
        }
    }
    private  String getRemoteAddress(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown"))
        {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
